package com.lagou.rpc.consumer.proxy;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.utils.ClazzUtils;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class RpcProxyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //获取com.lagou.rpc.api包下的所有类（不含子包）
        List<String> list = ClazzUtils.getClazzName("com.lagou.rpc.api", false);
        List<Class> classes = new ArrayList<>();
        for (String className : list) {
            try {
                classes.add(Class.forName(className));
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        //注册到 BeanDefinition
        for (Class aClass : classes) {
            //这里用到前面定义的FactoryBean
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RpcProxyFactoryBean.class);
            //生成beanDefinition
            GenericBeanDefinition beanDefinition = (GenericBeanDefinition)builder.getBeanDefinition();
            //将beanDefinition注册
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(aClass.getTypeName());
            beanDefinitionRegistry.registerBeanDefinition(aClass.getName(),beanDefinition);
        }
    }
}
